package main

import (
	"fmt"
	"os"

	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"techoiceness.com/aiagent/llm-gateway/internal/auth"
	"techoiceness.com/aiagent/llm-gateway/internal/config"
	"techoiceness.com/aiagent/llm-gateway/internal/database"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/logger"
)

var createUserCmd = &cobra.Command{
	Use:   "create-user <用户名> <密码>",
	Short: "创建新用户",
	Long:  `创建一个新的用户账户`,
	Args:  cobra.ExactArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		username := args[0]
		password := args[1]

		logger.Initialize()

		// 检查密码强度
		if len(password) < 6 {
			log.Error().Msg("错误: 密码长度必须至少为6个字符。")
			os.Exit(1)
		}

		log.Info().Msg("正在创建新用户...")
		cfg, err := config.LoadConfig()
		if err != nil {
			log.Error().Err(err).Msg("加载配置失败")
			os.Exit(1)
		}

		db, err := database.NewDatabase(&cfg.Database)
		if err != nil {
			log.Fatal().Err(err).Msg("连接数据库失败")
		}

		log.Info().Str("username", username).Msg("正在创建新用户...")

		// 检查用户名是否存在
		var count int64
		if err := db.Model(&entity.User{}).Where("username = ?", username).Count(&count).Error; err != nil {
			log.Fatal().Err(err).Str("username", username).Msg("检查用户名是否存在失败")
		}
		if count > 0 {
			log.Fatal().Str("username", username).Msg("用户名已存在")
		}

		// 加密密码
		passwordHash, err := auth.PasswordHash(password)
		if err != nil {
			log.Fatal().Err(err).Msg("密码加密失败")
		}

		// 创建用户
		user := entity.User{
			Username:     username,
			PasswordHash: passwordHash,
		}
		if err := db.Create(&user).Error; err != nil {
			log.Fatal().Err(err).Str("username", username).Msg("创建用户失败")
		}

		log.Info().Str("username", username).Str("user_id", user.ID.String()).Msg("用户创建成功")

		fmt.Printf("\n🎉 已成功创建用户:\n")
		fmt.Printf("   用户名: %s\n", username)
		fmt.Printf("   用户ID: %s\n", user.ID)
	},
}
